﻿using System;

using Microsoft.Xna.Framework;


namespace MainJumpFleet.SteerBehaviors
{
    public class Wander : SteeringBehavior
    {

        public Vector2 m_Target;

        public float m_fAimRandomly;

        public float m_fTurnSpeed;

        public float m_fAcceleration;

        public Random r;

        public Wander()
        {
            r = new Random();
        }

        public override void UpdateSteering(OakEngine.AI.Steering.Oak_Steering steer)
        {
            // Make sure we always have something to point at
            if (OakEngine.AI.Tools.OAK_AITools.SquareMagnitude(m_Target) == 0.0f)
            {
                m_Target = m_Agent.Position;
                m_Target.X += m_fAimRandomly;
                m_Target.Y += m_fAimRandomly;
            }

            Vector2 offSet = m_Target - m_Agent.Position;
            float angle;
            if (OakEngine.AI.Tools.OAK_AITools.SquareMagnitude(offSet) > 0)
            {
                // calcualte angel to destination
                angle = (float) Math.Atan2(offSet.Y, offSet.X);
            }
            else
            {
                // if are close to the target lets move away
                angle = 0;
            }

            // Move to target in a circle fasion
            m_Target = m_Agent.Position;
            m_Target.X += m_fAimRandomly*(float) Math.Cos(angle);
            m_Target.Y += m_fAimRandomly*(float) Math.Sign(angle);

            // add the turn to target 
            m_Target.X += MathHelper.Lerp(-m_fTurnSpeed, m_fTurnSpeed, (float)r.NextDouble());
            m_Target.Y += MathHelper.Lerp(-m_fTurnSpeed, m_fTurnSpeed, (float)r.NextDouble());

            // Seek stuff
            steer.ForwardVector = Vector2.Zero; ;
            steer.ForwardVector -= m_Agent.Position;

            if (OakEngine.AI.Tools.OAK_AITools.SquareMagnitude(steer.ForwardVector) > 0)
            {
                steer.ForwardVector = Vector2.Normalize(steer.ForwardVector);
                steer.ForwardVector *= m_fAcceleration;
            }
        }

    }
}
